<script>
export default {
  name: "CommonActionButtonGroup",
  data() {
    return {
      shownButtons: [],
    };
  },
  props: {
    triggerIcon: [Function, String],
    buttons: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    buttons: {
      handler(newVal) {
        this.watchButtonsChange(newVal);
      },
      immediate: true,
    },
  },
  render(h) {
    const children = [
      ...this.shownButtons.slice(0, 2).map((item) => {
        return h(
          "ElButton",
          {
            attrs: {
              type: "text",
            },
            size: "small",
            disabled: item.disabled,
            on: { click: () => this.handleCommand(item.name) },
          },
          this.renderText(h, item.text)
        );
      }),
    ];
    if (this.shownButtons.length > 2) {
      const items = [
        ...this.shownButtons.slice(2).map((item) => {
          return h(
            "ElDropdownItem",
            {
              key: item.name,
              attrs: {
                command: item.name,
                disabled: item.disabled,
                icon: item.icon,
                divided: item.divided,
              },
            },
            this.renderText(h, item.text)
          );
        }),
      ];
      const dropdown = h(
        "ElDropdown",
        {
          attrs: { ...this.$attrs },
          on: { ...this.$listeners, command: this.handleCommand },
        },
        [
          this.renderTrigger(h),
          h(
            "ElDropdownMenu",
            {
              slot: "dropdown",
            },
            items
          ),
        ]
      );
      children.push(dropdown);
    }
    return h("div", { class: "common-action-button-group" }, children);
  },
  methods: {
    renderTrigger(h) {
      let node;
      try {
        node = this.triggerIcon(h);
      } catch (error) {
        node = h("ElButton", {
          class: "more",
          attrs: {
            type: "text",
            icon: this.triggerIcon || "el-icon-more",
          },
          circle: true,
        });
      }
      return node;
    },
    renderText(h, text) {
      let node;
      try {
        node = text(h);
      } catch (error) {
        node = text;
      }
      return node;
    },
    watchButtonsChange(newVal) {
      if (typeof newVal === "object") {
        const shownButtons = [];
        Object.keys(newVal).map((key) => {
          const value = this.buttons[key];
          if (value.hidden) return;
          shownButtons.push({ name: key, ...value });
        });
        this.shownButtons = shownButtons;
      }
    },
    handleCommand(command) {
      this.$emit("command", command);
    },
  },
};
</script>

<style scoped>
>>> .more {
  transform: rotate(90deg);
  background: transparent;
  border: none;
  margin-left: 8px;
}
</style>
